package com.cssw.fyzb.tps.service.auth.tecent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cssw.fyzb.tps.exception.BizException;
import com.cssw.fyzb.tps.util.HttpUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cssw.fyzb.tps.util.Bizs.NONCE_TICKET_FAIL;

/**
 * 签名：合作方后台送身份信息时使用的签名
 *
 * @Author zhouxu
 * @create 2020-09-14 21:14
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class NONCETicket {

    private static final Logger logger = LoggerFactory.getLogger(NONCETicket.class);

    private String url;
    private String appId;
    /**
     * ticket 类型，默认值：NONCE（必须大写）
     */
    private String type;
    /**
     * 版本号
     */
    private String version;

    public HttpResult getNONCETicket(String userId, String accessToken) throws Exception {

        Map<String, Object> param = new HashMap<>();
        param.put("app_id", appId);
        param.put("access_token", accessToken);
        param.put("type", type);
        param.put("version", version);
        param.put("user_id", userId);
        logger.debug("params: " + JSON.toJSONString(param));

        long startTime = System.currentTimeMillis();
        String json = HttpUtil.get(url, param);
        long endTime = System.currentTimeMillis();
        logger.debug("userTime: " + (endTime - startTime));
        logger.debug(json);
        HttpResult result = parseResult(json);
        if (result == null || !HttpResult.STATUS_SUCCESS.equals(result.code)) {
            logger.error(json);
            String errmsg = null;
            if (result != null)
                errmsg = result.getMsg();
            throw new BizException(NONCE_TICKET_FAIL.code, NONCE_TICKET_FAIL.message + errmsg);
        }

        return result;
    }

    private HttpResult parseResult(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        String bizSeqNo = jsonObject.getString("bizSeqNo");
        String transactionTime = jsonObject.getString("transactionTime");
        Boolean success = jsonObject.getBoolean("success");

        HttpResult httpResult = new HttpResult();
        httpResult.setCode(code);
        httpResult.setMsg(msg);
        httpResult.setBizSeqNo(bizSeqNo);
        httpResult.setTransactionTime(transactionTime);
        httpResult.setSuccess(success);

        List<Ticket> tickets = new ArrayList<>();
        JSONObject object = null;
        Ticket ticket = null;
        JSONArray json_tickets = jsonObject.getJSONArray("tickets");
        if (json_tickets != null && json_tickets.size() > 0) {
            for (int i = 0; i < json_tickets.size(); i++) {
                object = json_tickets.getJSONObject(i);
                ticket = new Ticket();
                ticket.setValue(object.getString("value"));
                ticket.setExpire_in(object.getString("expire_in"));
                ticket.setExpire_time(object.getString("expire_time"));

                tickets.add(ticket);
            }
        }

        httpResult.setTickets(tickets);
        return httpResult;
    }


    /**
     * 出参报文：
     * {
     * "code": "0",
     * "msg": "请求成功",
     * "transactionTime": "20151022044027",
     * "tickets": [{
     * "value": "ticket_string",
     * "expire_in": "120",
     * "expire_time": "20151022044027"
     * }]
     * }
     */
    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class HttpResult {
        public static final String STATUS_SUCCESS = "0";

        private String code;
        private String msg;
        private String bizSeqNo;
        private boolean success;
        private String transactionTime;
        private List<Ticket> tickets;

    }

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public class Ticket {
        private String value;
        private String expire_in;
        private String expire_time;


    }


    public static void main(String[] args) throws Exception {
        String url = "https://idasc.webank.com/api/oauth2/api_ticket";
        //ID: TIDAD0fb
        //
        //Secret: h7g0DtzOTBHojWpLTqWr00YqmKKi1JnaPYjPFKSI8YJDblUKFm5EiTNqVksDFkHs
        String appId = "TIDAD0fb";
        String access_token = "WAA0f-dGGlQHTVClazkxtmW6FX_nRhpUB01QpWs5MbZluhXPolf1fdCczhHXuYA9ieeII_3PU92hBnQHhygUv81IGQ";
        String type = "NONCE";
        String version = "1.0.0";
        String userId = "user_id";

        NONCETicket nonceTicket = new NONCETicket();
        nonceTicket.setUrl(url);
        nonceTicket.setAppId(appId);
        nonceTicket.setType(type);
        nonceTicket.setVersion(version);


        HttpResult result = nonceTicket.getNONCETicket(userId, access_token);
        logger.debug(result.toString());
    }

}
